<template>
  <div>
    <div :id="id" />
    <input ref="files" style="display: none" type="file" accept="image/*" @change="uploadFile">
  </div>
</template>
<script>
import 'codemirror/lib/codemirror.css' // codemirror
import 'tui-editor/dist/tui-editor.css' // editor ui
import 'tui-editor/dist/tui-editor-contents.css' // editor content

import Editor from 'tui-editor'
import defaultOptions from './default-options'

// 定义的上传地址
import { getInfoFromOss } from '@/api/public'
import { randomString } from '@/utils'
import axios from 'axios'

export default {
  name: 'MarddownEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      required: false,
      default() {
        return 'markdown-editor-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    options: {
      type: Object,
      default() {
        return defaultOptions
      }
    },
    mode: {
      type: String,
      default: 'markdown'
    },
    height: {
      type: String,
      required: false,
      default: '300px'
    },
    language: {
      type: String,
      required: false,
      default: 'en_US' // https://github.com/nhnent/tui.editor/tree/master/src/js/langs
    }
  },
  data() {
    return {
      editor: null,
      token: ''
    }
  },
  computed: {
    editorOptions() {
      const options = Object.assign({}, defaultOptions, this.options)
      options.initialEditType = this.mode
      options.height = this.height
      options.language = this.language
      return options
    }
  },
  watch: {
    value(newValue, preValue) {
      if (newValue !== preValue && newValue !== this.editor.getValue()) {
        this.editor.setValue(newValue)
      }
    },
    language(val) {
      this.destroyEditor()
      this.initEditor()
    },
    height(newValue) {
      this.editor.height(newValue)
    },
    mode(newValue) {
      this.editor.changeMode(newValue)
    }
  },
  mounted() {
    this.initEditor()
  },
  destroyed() {
    this.destroyEditor()
  },
  methods: {
    initEditor() {
      this.editor = new Editor({
        el: document.getElementById(this.id),
        ...this.editorOptions
      })
      if (this.value) {
        this.editor.setValue(this.value)
      }
      this.editor.on('change', () => {
        this.$emit('input', this.editor.getValue())
      })
      // ----------------新增↓
      /*
        * 添加自定义按钮
        * */
      // 获取编辑器上的功能条
      const toolbar = this.editor.getUI().getToolbar()
      const fileDom = this.$refs.files
      // 添加事件
      this.editor.eventManager.addEventType('uploadEvent')
      this.editor.eventManager.listen('uploadEvent', () => {
        fileDom.click()
        this.getqiniuToken()
        // Do some other thing...
      })
      var fragment = document.createDocumentFragment()

      var button = document.createElement('button')
      button.setAttribute('class', 'custom-button a fa-image')

      // var iTag = document.createElement('i')
      // iTag.setAttribute('class', 'upload-img')
      // button.appendChild(iTag)

      fragment.appendChild(button)

      // 添加自定义按钮 第二个参数代表位置，不传默认放在最后
      toolbar.addButton({
        name: 'customize',
        className: 'tui-image',
        event: 'uploadEvent',
        tooltip: '插入图片',
        el: fragment.appendChild(button)
      }, 13)
    },
    // ----------------新增↑
    destroyEditor() {
      if (!this.editor) return
      this.editor.off('change')
      this.editor.remove()
    },
    setValue(value) {
      this.editor.setValue(value)
    },
    getValue() {
      return this.editor.getValue()
    },
    setHtml(value) {
      this.editor.setHtml(value)
    },
    getHtml() {
      return this.editor.getHtml()
    },
    // ----------------新增↓
    /*
      * 自定义上传图片处理
      * */
    uploadFile(e) {
      const target = e.target
      const file = target.files[0]
      // const formData = new FormData()
      // formData.append('file', file)
      // const _file = this.dataURLtoBlob() //  base64转换为 blob

      getInfoFromOss().then(response => {
        console.log(response)
        const info = response.data

        const randomStr = randomString(13)
        const param = new FormData()
        param.append('key', randomStr)
        param.append('policy', info.policy)
        param.append('OSSAccessKeyId', info.accessKeyId)
        param.append('success_action_status', 200)
        param.append('signature', info.signature)
        param.append('file', file)
        param.append('chunk', '0')
        const config = {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Access-Control-Allow-Origin': '*'
          }
        }
        axios.post(info.host, param, config)
          .then(response => {
            console.log('图片提交成功')
            console.log(response)
            if (response.status === 200) {
              this.$message({ message: '图片上传成功', type: 'success' })
            } else {
              this.$message({ message: '图片上传失败', type: 'error' })
            }
            const imgUrl = info.host + '/' + randomStr
            console.log(imgUrl, 'imgUrl')
            this.addImgToMd(imgUrl)
          })
      })
      target.value = ''// 这个地方清除一下不然会有问题
    },
    // 添加图片到markdown
    addImgToMd(data) {
      const editor = this.editor.getCodeMirror()
      const editorHtml = this.editor.getCurrentModeEditor()
      const isMarkdownMode = this.editor.isMarkdownMode()
      if (isMarkdownMode) {
        editor.replaceSelection(`![img](${data})`)
      } else {
        const range = editorHtml.getRange()
        const img = document.createElement('img')
        img.src = `${data}`
        img.alt = 'img'
        range.insertNode(img)
      }
    },
    getqiniuToken() {

    }
    // ----------------新增↑
  }
}
</script>
